package com.wryyyyy.scoket;

import cn.hutool.json.JSONUtil;
import com.wryyyyy.dto.SessionBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class MyWsHandler extends AbstractWebSocketHandler {
    private static final Map<String, SessionBean> sessionBeanMap;
    private static final AtomicInteger clientIdMaker;

    private static final Map<String, List<String>> clientArgument;

    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(0);
        clientArgument = new ConcurrentHashMap<>();
    }

    public static Map<String, SessionBean> getMap() {
        return sessionBeanMap;
    }

    public static Map<String, List<String>> getArgs() {
        return clientArgument;
    }

    // 连接建立
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        SessionBean sessionBean = new SessionBean(session, clientIdMaker.getAndIncrement());
        sessionBeanMap.put(session.getId(), sessionBean);
        clientArgument.put(session.getId(), new ArrayList<>());
    }

    //收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String argStr = message.getPayload();

        List<String> argList = JSONUtil.parseArray(argStr).toList(String.class);
        clientArgument.put(session.getId(), argList);

        log.info(sessionBeanMap.get(session.getId()).getClientId() + " : " + message.getPayload());
    }

    //传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if (session.isOpen()) {
            session.close();
        }
        sessionBeanMap.remove(session.getId());
        clientArgument.remove(session.getId());
    }

    // 连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        clientArgument.remove(session.getId());
        log.info(sessionBeanMap.get(session.getId()).getClientId() + "关闭了连接");
    }

    // 每2s发送给客户端心跳消息
//    @Scheduled(fixedRate = 2000)
    public void sendMsg() throws IOException {
        for (String key : sessionBeanMap.keySet()) {
            sessionBeanMap.get(key).getWebSocketSession().sendMessage(new TextMessage("服务器消息-_-!"));
        }
    }
}